package myaction.teacher;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class TeacherSelectCourseAction extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
//        当前课程编号
        String id = request.getParameter("id");
        String c_id = null;
        String c_name = null;
        String c_time = null;
        String c_teacher_id = null;
        String c_teacher_name = null;
        String s_id = String.valueOf(session.getAttribute("teacher_id"));
        String s_name = String.valueOf(session.getAttribute("teacher_name"));
//        判断所要教的课程是否已经有老师教授
//        此课程现在的教师
        int teacher_flag = Integer.parseInt(request.getParameter("c_teacher_id"));
        System.out.println("teacher_flag:" + teacher_flag);
        if (teacher_flag != 0) {
//            若已经有人教授，输出
            System.out.println("此课程已有授课教师");
            request.setAttribute("teacher_select_repeat", "此课程已有授课教师!");
            request.getRequestDispatcher("TeacherCoursesFindAll").forward(request, response);
        } else {
//        若还无人教授，设置授课教师为此教师，根据session获取此教师id
            try {
                String sql = "update t_courses set c_teacher_id=?,c_isable='1' where c_id=?";
                Connection conn = DbUtil.getConn();
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setInt(1, Integer.parseInt(s_id));
                ps.setInt(2, Integer.parseInt(id));
                ps.executeUpdate();
                ps.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("此课程无授课教师，已设置为" + s_name);
            response.sendRedirect("TeacherCoursesFindAll");
        }
        System.out.println("TeacherSelectCourseAction");
    }
}
